<?php
/**
 * CpController
 * 
 * @author
 * @version 
 */
require_once 'Zend/Controller/Action.php';
class Admin_GpageController extends Sunnet_Controller_Action
{
	var $_arrParam;
	public function init()
    {
//    	Truyền các tham số nhận được ra view
    	$this->_arrParam = $this->_request->getParams();
    	$this->view->arrParam = $this->_arrParam;
    	if (empty($this->_arrParam['page'])) {
    		$this->_arrParam['page'] = 1;
    	}

    	if (empty($this->_arrParam['line_per_page'])) {
    		$this->_arrParam['line_per_page'] = 10;
    	}

        Zend_Loader::loadClass('Admin_Models_MenuModel');
         $db = new Admin_Models_MenuModel();
         $mainmenu = $db->loadmainmenu();
         $this->view->mainmenu = $mainmenu; 
         
         function vn_str_filter ($str){
			$unicode = array(
					'a'=>'á|à|ả|ã|ạ|ă|ắ|ặ|ằ|ẳ|ẵ|â|ấ|ầ|ẩ|ẫ|ậ',
					'd'=>'đ',
					'e'=>'é|è|ẻ|ẽ|ẹ|ê|ế|ề|ể|ễ|ệ',
					'i'=>'í|ì|ỉ|ĩ|ị',
					'o'=>'ó|ò|ỏ|õ|ọ|ô|ố|ồ|ổ|ỗ|ộ|ơ|ớ|ờ|ở|ỡ|ợ',
					'u'=>'ú|ù|ủ|ũ|ụ|ư|ứ|ừ|ử|ữ|ự',
					'y'=>'ý|ỳ|ỷ|ỹ|ỵ',
					'A'=>'Á|À|Ả|Ã|Ạ|Ă|Ắ|Ặ|Ằ|Ẳ|Ẵ|Â|Ấ|Ầ|Ẩ|Ẫ|Ậ',
					'D'=>'Đ',
					'E'=>'É|È|Ẻ|Ẽ|Ẹ|Ê|Ế|Ề|Ể|Ễ|Ệ',
					'I'=>'Í|Ì|Ỉ|Ĩ|Ị',
					'O'=>'Ó|Ò|Ỏ|Õ|Ọ|Ô|Ố|Ồ|Ổ|Ỗ|Ộ|Ơ|Ớ|Ờ|Ở|Ỡ|Ợ',
					'U'=>'Ú|Ù|Ủ|Ũ|Ụ|Ư|Ứ|Ừ|Ử|Ữ|Ự',
					'Y'=>'Ý|Ỳ|Ỷ|Ỹ|Ỵ',
					'_'=>' ',
			);
		
			foreach($unicode as $nonUnicode=>$uni){
				$str = preg_replace("/($uni)/i", $nonUnicode, $str);
			}
			return $str;
		}
    }

    public function preDispatch(){
        $this->view->headScript()->appendFile('/js/ckeditor/ckeditor.js','text/javascript');
         $template_path = TEMPLATE_PATH . "/admin/default/";
		$this->loadTemplate($template_path,'template.ini','template');           
    	$auth = Zend_Auth::getInstance();
        $this->view->userName = $auth->getIdentity()->username;
    	if ((!$auth->hasIdentity() || !$auth->getIdentity()->admin) && ($this->_arrParam['action'] != 'login')) {
    		$this->_forward('login','index','admin',array('action'	=> 'login'));//,$this->_arrParam);
    	}
        $this->view->headScript()->appendFile('/js/ckeditor/ckeditor.js','text/javascript');
        $this->view->headScript()->appendFile('/js/ckeditor/styles.js','text/javascript');
        $this->view->headScript()->appendFile('/js/ckeditor/ckeditor.css','text/css');
    }
    /**
     * The default action - show the home page
     */
    public function reorderProcessAction(){
        $this->_helper->layout->disableLayout();
        Zend_loader::loadClass('Admin_Models_GpageModel');
        $model_group = new Admin_Models_GpageModel();
        $id=0;
        foreach ($_GET['listItem'] as $position => $item) :
	//ban thuc hien cau lenh insert tai day 
        //$sql[] = "UPDATE `tbl_groupnote` SET `ordering` = $position WHERE `GroupNoteID` = $item";
       
        $where ='GroupNoteID = '. $item;
       // Zend_debug::dump($where);
        //echo $item.":"; echo $position."-";
        
        try{
        $result=$model_group->update(array('ordering'=>$position),$where );
        $id++;
        }catch(Exception $e){
            $id--;
        }
        endforeach;
//         print_r($sql);
//        die;
        if($id>0) echo 'Update success';else echo 'Update fail';
         
    }
    public function reorderAction(){
          Zend_loader::loadClass('Admin_Models_GpageModel');
          $model_group = new Admin_Models_GpageModel();
          $listgroup  = $model_group->loadlistgrouptoorder();
           $request = $this->getRequest();
          $List_order = $request->getParam('listItem[]');
          if($List_order==null){
                $this->view->listorder = $listgroup;
          }else{
              Zend_debug::dump($List_order);
              return 'success';
          }                  
    }

    public function indexAction(){
         Zend_loader::loadClass('Admin_Models_GpageModel');
//		Load các model và form sử dụng trong action
         $search = $this->_request->getParam('search');
         $field  = $this->_request->getParam('field');
         $group_id  = $this->_request->getParam('group_field');
         
         $db_listnote = new Admin_Models_GpageModel();
         $listnote = $db_listnote->listnote();
         $this->view->note_group_list = $db_listnote->loadNoteGroup();
         $currentPage = 1;
		$i = $this->_getParam('page',1);
		if(!empty($i))
		{
			$currentPage = $i;
		}

		$paginator = Zend_Paginator::factory($listnote);

		$paginator->setItemCountPerPage(10)
		->setPageRange(4)
		->setCurrentPageNumber($currentPage);
		$this->view->paginator = $paginator;
         if($search!= null || $field!= null || $group_id!=null){    
            
              $listnote = $db_listnote->search($search, $field,$group_id);
         
         $currentPage = 1;
		$i = $this->_getParam('page',1);
		if(!empty($i))
		{
			$currentPage = $i;
		}
		$paginator = Zend_Paginator::factory($listnote);

		$paginator->setItemCountPerPage(10)
		->setPageRange(4)
		->setCurrentPageNumber($currentPage);
		$this->view->paginator = $paginator;
                $this->view->note_group_list = $db_listnote->loadNoteGroup();
         }          
    }

    public function addNoteAction(){
        Zend_loader::loadClass('Admin_Forms_AddNoteForm');
        Zend_loader::loadClass('Admin_Models_GpageModel');
        $session = new Zend_Session_Namespace();

        $model_group  = new Admin_Models_GpageModel();
        $form = new Admin_Forms_AddNoteForm($model_group->loadNoteGroup(),null);
        //Zend_debug::dump($form);
      
       $this->view->form = $form;
       $request=$this->getRequest();
				
		if($request->isPost()){
			//lay title alias theo title
				$filename = $this->_request->getParam('note_name');
				$filename = addslashes($filename);
				
				$filename_cut = vn_str_filter(trim($filename));

				try {
				$validator= $this->_request->getParams();
				if(is_array($form->avatar->getFileName(null,false))== false){
				$info = pathinfo($form->avatar->getFileName(null,false));
				
				$ext = $info['extension']?".".$info['extension']:"";
				//filter for renaming.. prepend with current time
				$form->avatar->addFilter(new Zend_Filter_File_Rename(array(
						"target"=>$filename_cut.'_'.time().$ext,
						"overwrite"=>true)));
				$form->getValue('avatar');
				$imgpath= '/imagesnote/note/'.$filename_cut.'_'.time().$ext;
				$image = UPLOAD_PATH.'/imagesnote/note/'.$filename_cut.'_'.time().$ext;
                                
				$thumb = new WJG_Resource_Thumbnail($image,90,90);
                               $name_320 = pathinfo($thumb->img_320);
                               $name_480 = pathinfo($thumb->img_480);
                               $name_800 = pathinfo($thumb->img_800);
                           
				$image_320 = '/imagesnote/thumb_note/'.$name_320['filename'].$ext;
                                $image_480 = '/imagesnote/medium_note/'.$name_480['filename'].$ext;
                                $image_800 = '/imagesnote/note/'.$name_800['filename'].$ext;
				}else{
					$imgpath= null;
					$image_320 = null;
                                        $image_480 = null;
                                        $image_800 = null;
				}
				if ($form->isValid($validator)==FALSE){
						$this->view->messagesError = $form->getMessagesError();
				}else {
					// insert bang moi vao useractivity 
                                        //insert note vao database                                      
                                        $db= new Admin_Models_GpageModel();
										
										$data= array(
												'UserID'=>  $session->userid,
												'content_note'=>$this->_request->getParam('feature'),
												'GroupNoteID'=>$this->_request->getParam('GroupNoteID'),
												'link_images_thumb'=>$image_320,
					                            'link_images_medium'=>$image_480,
					                            'link_images'=>$image_800,    
					                            'description'=>$this->_request->getParam('description'),
												'name_note'=>$this->_request->getParam('note_name'),												
												'link_url'=>$this->_request->getParam('link_url'),
												'title_alias' => $filename_cut,

												'seo_title'=>$this->_request->getParam('seo_title'),
                                               	'seo_keywords'=>$this->_request->getParam('seo_keywords'),
                                               	'seo_description'=>$this->_request->getParam('seo_description'),
										);

										try{
					                        $result = $db->addNote($data);

										}catch(Exception $e)
										{
											echo $e;
										}

									if($result>0)
									{
										// /alert('Note added');
										echo "<script>window.location = '/admin/gpage/';</script>";
										
									}else {
										echo "<script>alert('Add note Fail');window.location = '/admin/gpage/';</script>";
									}
					
				}
				
				
				} catch (Exception $e) {
					echo $e;
				}
					
		}
		
    }
    
    public function editNoteAction(){
         $id = $this->_request->getParam('id');
        Zend_loader::loadclass('Admin_Models_GpageModel');
        Zend_loader::loadclass('Admin_Forms_EditNoteForm');
        $session = new Zend_Session_Namespace();

        $db_edit_note = new Admin_Models_GpageModel();
        $result_edit = $db_edit_note->loadnotebyid($id);
        $listgroup = $db_edit_note->loadNoteGroup();
        $form = new Admin_Forms_EditNoteForm($result_edit, $listgroup);
        $this->view->form=$form;
        $this->view->data = $result_edit;
        $request=$this->getRequest();
        if($request->isPost()){
			//lay title alias
				$filename = $this->_request->getParam('note_name');
				$filename_cut = vn_str_filter(trim($filename));

				try {
				$validator= $this->_request->getParams();
				if(is_array($form->avatar->getFileName(null,false))== false){
				$info = pathinfo($form->avatar->getFileName(null,false));
				
				$ext = $info['extension']?".".$info['extension']:"";
	 			//filter for renaming.. prepend with current time
				$form->avatar->addFilter(new Zend_Filter_File_Rename(array(
						"target"=>$filename_cut.'_'.time().$ext,
						"overwrite"=>true)));
				$form->getValue('avatar');
				$imgpath= '/imagesnote/note/'.$filename_cut.'_'.time().$ext;
				$image = UPLOAD_PATH.'/imagesnote/note/'.$filename_cut.'_'.time().$ext;
				$thumb = new WJG_Resource_Thumbnail($image,90,90);
				 $name_320 = pathinfo($thumb->img_320);
                               $name_480 = pathinfo($thumb->img_480);
                               $name_800 = pathinfo($thumb->img_800);
                           
				$image_320 = '/imagesnote/thumb_note/'.$name_320['filename'].$ext;
                                $image_480 = '/imagesnote/medium_note/'.$name_480['filename'].$ext;
                                $image_800 = '/imagesnote/note/'.$name_800['filename'].$ext;
				}else{
					$imgpath= null;
					$image_320 = null;
                                        $image_480 = null;
                                        $image_800 = null;
				}
				if ($form->isValid($validator)==FALSE){
						$this->view->messagesError = $form->getMessagesError();
				}else {
				
                                        //insert note lay UserActivity
                                    if($imgpath!= null){
											$data= array(												
												'UserID'=>  $session->userid,
												'content_note'=>$this->_request->getParam('feature'),
												'GroupNoteID'=>$this->_request->getParam('GroupNoteID'),
												'link_images_thumb'=>$image_320,
					                            'link_images_medium'=>$image_480,
					                            'link_images'=>$image_800,    
					                            'description'=>$this->_request->getParam('description'),
												'name_note'=>$this->_request->getParam('note_name'),												
												'link_url'=>$this->_request->getParam('link_url'),
												'title_alias' => $filename_cut,

												'seo_title'=>$this->_request->getParam('seo_title'),
                                               	'seo_keywords'=>$this->_request->getParam('seo_keywords'),
                                               	'seo_description'=>$this->_request->getParam('seo_description')

                                            );
									}else{
                                            $data= array(												
												'UserID'=>  $session->userid,
												'content_note'=>$this->_request->getParam('feature'),
												'GroupNoteID'=>$this->_request->getParam('GroupNoteID'),
	
					                            'description'=>$this->_request->getParam('description'),
												'name_note'=>$this->_request->getParam('note_name'),												
												'link_url'=>$this->_request->getParam('link_url'),
												'title_alias' => $filename_cut,

												'seo_title'=>$this->_request->getParam('seo_title'),
                                               	'seo_keywords'=>$this->_request->getParam('seo_keywords'),
                                               	'seo_description'=>$this->_request->getParam('seo_description')
                                            );  
                            		}	
					try{
					       $db= new Admin_Models_GpageModel();
                           $result = $db_edit_note->updatenote($data,$id);

                           if($result_edit[0]['GroupNoteID']!= $data['GroupNoteID']){
                           		$where = $db->getAdapter()->quoteInto("GroupNoteID = ? ", $this->_request->getParam('GroupNoteID'));
                           		$result1 = $db->update(array('count_note'	=> new Zend_Db_Expr('`count_note` + 1')), $where);

                           		$where_old = $db->getAdapter()->quoteInto("GroupNoteID = ? ", $result_edit[0]['GroupNoteID']);
                           		$result1 = $db->update(array('count_note'	=> new Zend_Db_Expr('`count_note` - 1')), $where_old);
                           }           
                                             
                    }catch(Exception $e)
						{
							echo $e;
						}
					if($result>0)
					{
						//alert('Post added');
						echo "<script>window.location = '/admin/gpage/';</script>";
		   				
					}else {
						echo "<script>alert('Add Post Fail');window.location = '/admin/gpage/';</script>";
					}
					
				}
								
				} catch (Exception $e) {
					echo $e;
				}
			
		
		}
    }

    public function addNoteGroupAction(){
        Zend_loader::loadClass('Admin_Forms_AddNoteGroupForm');
        Zend_loader::loadClass('Admin_Models_GpageModel');
      
        //Zend_debug::dump($form);
       $model_group  = new Admin_Models_GpageModel();
         $form = new Admin_Forms_AddNoteGroupForm($model_group->loadNoteGroup(),null);
       //Zend_debug::dump($model_group->loadNoteGroup());
       $this->view->form = $form;
       $request=$this->getRequest();
				
		if($request->isPost()){
			//lay title alias
				$filename = $this->_request->getParam('groupname');
				$filename_cut = vn_str_filter(trim($filename));
				try {
				$validator= $this->_request->getParams();
				if(is_array($form->avatar->getFileName(null,false))== false){
				$info = pathinfo($form->avatar->getFileName(null,false));
								
				$ext = $info['extension']?".".$info['extension']:"";
				//filter for renaming.. prepend with current time
				$form->avatar->addFilter(new Zend_Filter_File_Rename(array(
						"target"=>$filename_cut.'_'.time().$ext,
						"overwrite"=>true)));
				$form->getValue('avatar');
				$image = '/images/thaoluan/'.$filename_cut.'_'.time().$ext;
				}else{
						$image = null; 	
				}
				if ($form->isValid($validator)==FALSE){
						$this->view->messagesError = $form->getMessagesError();
				}else {
					
					
						$data= array(
                                               'UserID'=>'sauthienthu',
                                               'name_group'=>$this->_request->getParam('groupname'),
                                               'image_group' => $image,
                                               'parent'=>$this->_request->getParam('GroupNoteID'),
                                               'main_event'=>$this->_request->getParam('main_event'),
                                               'images_full'=>$this->_request->getParam('images_full'),
                                               'onlyadminpost'=>$this->_request->getParam('onlyadminpost'),
                                               'title_alias' => $filename_cut,

                                               'seo_title'=>$this->_request->getParam('seo_title'),
                                               'seo_keywords'=>$this->_request->getParam('seo_keywords'),
                                               'seo_description'=>$this->_request->getParam('seo_description'),
                                                    
					);
					
					try{
						
					$db= new Admin_Models_GpageModel();
                              
					$result=$db->addNoteGroup($data);
					}catch(Exception $e)
					{
						echo $e;
					}
					if($result>0)
					{
						//alert('Group added');
						echo "<script>window.location = '/admin/gpage/list-group/';</script>";
						
					}else {
						echo "<script>alert('Add Group Fail');window.location = '/admin/gpage/list-group/';</script>";
					}
					
				}
				
				
				} catch (Exception $e) {
					echo $e;
				}
			
		
		}
    }

    public function editGroupAction(){
        $id = $this->_request->getParam('id');
        Zend_loader::loadclass('Admin_Models_GpageModel');
        Zend_loader::loadclass('Admin_Forms_EditNoteGroupForm');
       
        $db_edit_group = new Admin_Models_GpageModel();
        $result = $db_edit_group->loadgroupnamebyid($id);
        $listgroup = $db_edit_group->loadNoteGroup();
        $form = new Admin_Forms_EditNoteGroupForm($result, $listgroup);
        $this->view->form=$form;
         $this->view->data = $result;
         $request=$this->getRequest();
				
		if($request->isPost()){
			//alias title
				$filename = $this->_request->getParam('groupname');
				$filename_cut = vn_str_filter(trim($filename));
				try {
				$validator= $this->_request->getParams();
				if(is_array($form->avatar->getFileName(null,false))== false){
				$info = pathinfo($form->avatar->getFileName(null,false));
								
				$ext = $info['extension']?".".$info['extension']:"";
				//filter for renaming.. prepend with current time
				$form->avatar->addFilter(new Zend_Filter_File_Rename(array(
						"target"=>$filename_cut.'_'.time().$ext,
						"overwrite"=>true)));
				$form->getValue('avatar');
				$image = '/images/thaoluan/'.$filename_cut.'_'.time().$ext;
				}else{
						$image = null; 	
				}
				if ($form->isValid($validator)==FALSE){
						$this->view->messagesError = $form->getMessagesError();
				}else {
					
					       if($image== null){
                                                   $data= array(
                                               'UserID'=>'sauthienthu',
                                               'name_group'=>$this->_request->getParam('groupname'),
                                               'parent'=>$this->_request->getParam('GroupNoteID'),
                                               'main_event'=>$this->_request->getParam('main_event'),
                                               'images_full'=>$this->_request->getParam('images_full'),
                                               'onlyadminpost'=>$this->_request->getParam('onlyadminpost'),
                                               'title_alias' => $filename_cut,

                                               'seo_title'=>$this->_request->getParam('seo_title'),
                                               'seo_keywords'=>$this->_request->getParam('seo_keywords'),
                                               'seo_description'=>$this->_request->getParam('seo_description'),

                                                );
                                               }else{
						$data= array(
                                               'UserID'=>'sauthienthu',
                                               'name_group'=>$this->_request->getParam('groupname'),
                                               'image_group' => $image,
                                               'parent'=>$this->_request->getParam('GroupNoteID'),
                                               'main_event'=>$this->_request->getParam('main_event'),
                                               'images_full'=>$this->_request->getParam('images_full'),
                                               'onlyadminpost'=>$this->_request->getParam('onlyadminpost'),
                                               'title_alias' => $filename_cut,

                                               'seo_title'=>$this->_request->getParam('seo_title'),
                                               'seo_keywords'=>$this->_request->getParam('seo_keywords'),
                                               'seo_description'=>$this->_request->getParam('seo_description'),
					);     
                                               }
					try{
						
					$db= new Admin_Models_GpageModel();
					$where = $db->getAdapter()->quoteInto("GroupNoteID = ? ", $this->_request->getParam('GroupNoteID'));
					$result1 = $db->update(array('count_note'	=> new Zend_Db_Expr('`count_note` + 1')), $where);
		        
					$result=$db->updatenotegroup($data,$id);
					}catch(Exception $e)
					{
						echo $e;
					}
					if($result>0)
					{
						//alert('Group edited');
						echo "<script>window.location = '/admin/gpage/list-group';</script>";
						
					}else {
						echo "<script>alert('EDit Group Fail');window.location = '/admin/gpage/list-group';</script>";
					}
					
				}
				
				
				} catch (Exception $e) {
					echo $e;
				}
			
		
		}
    }

    public function delNoteAction(){
       $id = $this->_request->getParam('id');
       Zend_loader::loadclass('Admin_Models_GpageModel');

       $db_del_note  = new Admin_Models_GpageModel();

       $result = $db_del_note->delnote($id);

        if($result>0)
		{
			echo "<script>alert('Xóa bài viết thành công ');window.location = '/admin/gpage/index/';</script>";
		}else {		
			echo "<script>alert('Xóa bài viết thất bại');window.location = '/admin/gpage/index';</script>";
		}
    }

    public function delNoteGroupAction(){
       $groupid = $this->_request->getParam('id');
       Zend_loader::loadclass('Admin_Models_GpageModel');
       $db_del_group  = new Admin_Models_GpageModel();
       $result = $db_del_group->delgroupnote($groupid);
     
       if($result>0)
		{
			//<script>alert('Xóa note thành công ');
                      echo "window.location = '/admin/gpage/list-group/';</script>";
		}else {		
			echo "<script>alert('Delete device Fail');window.location = '/admin/gpage/list-group';</script>";
		}
    }
    public function listGroupAction(){
        Zend_loader::loadClass('Admin_Models_GpageModel');
         $template_path = TEMPLATE_PATH . "/admin/default/";
		$this->loadTemplate($template_path,'template.ini','template');
//		Load các model và form sử dụng trong action
         $db_listgroup = new Admin_Models_GpageModel();
         $listgroup = $db_listgroup->listgroup();
         
         $currentPage = 1;
		$i = $this->_getParam('page',1);
		if(!empty($i))
		{
			$currentPage = $i;
		}
		$paginator = Zend_Paginator::factory($listgroup);

		$paginator->setItemCountPerPage(10)
		->setPageRange(4)
		->setCurrentPageNumber($currentPage);
		$this->view->paginator = $paginator;
                
    }
	
}
